﻿/*
 * Created by SharpDevelop.
 * User: StrunevskyDV
 * Date: 03.03.2010
 * Time: 16:34
 * 
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */
using System;
using FinancialPersonal.Entities;
using System.Collections;
using System.Collections.Generic;
using EmailJabber.Logic.Logic.BusinessLogic;

namespace FinancialPersonal.Logic
{
	/// <summary>
	/// Description of FinanceLogic.
	/// </summary>
	public class FinanceLogic
	{
		private static FinanceLogic instance = new FinanceLogic();
		private Dictionary<string, UserEntity> usersCache = new Dictionary<string, UserEntity>();

		private Dictionary<Guid, object> states = new Dictionary<Guid, object>();
		
		public static FinanceLogic Instance
		{
			get
			{
				return instance;
			}
		}

		private FinanceLogic()
		{
			
		}
		
		public Dictionary<Guid, object> States {
			get { return states; }
			set { states = value; }
		}
		
		
		private UserEntity CreateUser(string Jid)
		{
			UserEntity user;
			user = new UserEntity();
			user.Id = Guid.NewGuid();
			user.Jid = Jid;
			user.RepetatedPayment = new List<RepeatedOutcomeEntity>();
			user.Goals = new List<GoalEntity>();
			EntitiesBlo.Instance.StoreEntity(user);
			return user;
		}
		
		public List<GoalEntity> GetGoals(string userJid)
		{
			Guid userId = GetUserByJid(userJid).Id;
			var result = EntitiesBlo.Instance.FindEntity<GoalEntity>(item => item.UserId.Equals(userId));
			return (List<GoalEntity>) result;
		}
		
		public IList<UserEntity> GetAllUsers()
		{
			return EntitiesBlo.Instance.FindEntity(new Predicate<UserEntity>( item => item != null ));
		}
		
		public UserEntity GetUserByJid(string jid)
		{
			UserEntity result = null;
			
			var items = EntitiesBlo.Instance.FindEntity<UserEntity>(item => item.Jid.Equals(jid));
			if(items.Count>0)
			{
				usersCache[jid] = items[0];
				result = usersCache[jid];
			}
			else
			{
				result = CreateUser(jid);
			}
			return result;
		}
		
		public void StoreUser(UserEntity user)
		{
			EntitiesBlo.Instance.StoreEntity(user);
		}
		
		public RepeatedOutcomeEntity GetRepeatedOutcomeEntityById(Guid id)
		{
			return (RepeatedOutcomeEntity) EntitiesBlo.Instance.GetEntityById(id);
		}
	}
}
